import router from "@/router";
import { useUserStore, useRouteStore } from "@/stores";
import { Message } from "@arco-design/web-vue";
import { getToken } from "@/utils/auth";
import { isHttp } from "@/utils/validate";

const whiteList = ["/login", "/register"];
let hasRouteFlag = false;
export const resetHasRouteFlag = () => {
  hasRouteFlag = false;
};

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore();
  const routeStore = useRouteStore();
  if (getToken()) {
    if (to.path === "/login") {
      next();
    } else if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      const isEmpty = Object.getOwnPropertyNames(userStore.userInfo).length;
      if (!isEmpty) {
        try {
          await userStore.getInfo();
          await userStore.getTenantList();
          const accessRoutes = await routeStore.generateRoutes();
          accessRoutes.forEach(route => {
            if (!isHttp(route.path)) {
              router.addRoute(route);
            }
          });
          next({ ...to, replace: true });
        } catch (error) {
          userStore.resetToken();
          Message.error("用户信息或者路由加载异常，请重新登录");
          next(`/login`);
        }
      } else {
        next();
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next();
    } else {
      Message.error("登录已过期，请重新登陆！");
      next("/login");
    }
  }
});
